package com.fmi.timedealer.moodtracking;

import java.util.Date;

import com.fmi.timedealer.R;
import com.fmi.timedealer.datamanager.IDataManager;
import com.fmi.timedealer.datamanager.SQLiteDataManager;

import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class UpdateMoodActivity extends ListActivity{

	private MoodsAdapter adapter;
	private IDataManager dbManager = null;
	private Mood currentSelection = null;
	
	private final static Mood[] moods;
	
	static {
		moods = Mood.values();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.mood_update);

		dbManager = new SQLiteDataManager("MyDB", this);

		adapter = new MoodsAdapter(this, R.layout.mood_item);
		adapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
		setListAdapter(adapter);

		getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		getListView().setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

				currentSelection = moods[position];
				boolean success = dbManager.updateMood(new TrackedMood(currentSelection.getCode(), new Date(), null));
				
				if(success) {
					Toast.makeText(getApplicationContext(), "Successfully updated mood", Toast.LENGTH_SHORT).show();
				}
				else {
					Toast.makeText(getApplicationContext(), "A technical problem occured, mood is not updated", Toast.LENGTH_SHORT).show();
				}
				finish();
			}
		});
	}

	private class MoodsAdapter extends ArrayAdapter<Mood> {

		public MoodsAdapter(Context context, int textViewRecourceId) {
			super(context, textViewRecourceId);
			
			for(Mood mood : moods) {
				add(mood);
			}
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			View v = (View) convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = (View) vi.inflate(R.layout.mood_item, null);
			}
			
			Mood mood = moods[position];

			if (mood != null) {
				
				TextView tv = (TextView) v.findViewById(R.id.moodLable);
				tv.setText(mood.getLabel());
			
				ImageView iv = (ImageView) v.findViewById(R.id.moodIcon);
				iv.setImageResource(mood.getIcon());
			}
			return v;
		}
	}
}
